<!--
 * @Author: coffee
 * @Date: 2025-08-20 09:54:16
 * @LastEditors: coffee 18600726405@163.com
 * @LastEditTime: 2025-08-22 16:39:39
 * @Descripttion: 低代码
 * @FilePath: \vue3-element-admin-master\src\views\dashboard\index.vue
-->
<template>
  <!-- <el-card shadow="never" class="mt-2">
      <div class="flex flex-wrap">
        <div class="flex-1 flex items-start">
          <img
            class="w80px h80px rounded-full"
            :src="userStore.userInfo.avatar + '?imageView2/1/w/80/h/80'"
          />
          <div class="ml-5">
            <p>{{ greetings }}</p>
            <p class="text-sm text-gray">今日天气晴朗，气温在15℃至25℃之间，东南风。</p>
          </div>
        </div>
      </div>
    </el-card>

    <el-row :gutter="10" class="mt-5">
      <el-col :xs="24" :span="24">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span>访问趋势</span>
              <el-radio-group v-model="visitTrendDateRange" size="small">
                <el-radio-button :value="7">近7天</el-radio-button>
                <el-radio-button :value="30">近30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <VChart class="chart" :option="option" />
        </el-card>
      </el-col>
    </el-row> -->
  <div>
    <div id="homeBoard" class="main">
      <div class="board-head">
        <div class="head-bg">
          <img class="logo" src="../../assets/homepage/logo.png" alt="" />
          <img class="yibiao" src="../../assets/homepage/yibiao.png" alt="" />
          <span></span>
        </div>
        <!-- <img style="cursor: pointer;" @click="reLoadPage" src="./imgs/shuaxin.png" alt="" /> -->
        <img
          style="cursor: pointer"
          src="../../assets/homepage/shuaxin.png"
          alt=""
          @click="reload"
        />
      </div>
      <div class="board-main">
        <div class="main-left"></div>
        <div class="main-center"></div>
        <div class="main-right"></div>
      </div>
      <div class="foot-bg"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});

import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { PieChart } from "echarts/charts";
import { TitleComponent, TooltipComponent, LegendComponent } from "echarts/components";
import VChart from "vue-echarts";

import { dayjs } from "element-plus";
import LogAPI, { VisitStatsVO, VisitTrendVO } from "@/api/system/log.api";
import { useUserStore } from "@/store/modules/user.store";
import { useOnlineCount } from "@/composables/useOnlineCount";

use([CanvasRenderer, PieChart, TitleComponent, TooltipComponent, LegendComponent]);

const option = ref({
  title: {
    text: "Traffic Sources",
    left: "center",
  },
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b} : {c} ({d}%)",
  },
  legend: {
    orient: "vertical",
    left: "left",
    data: ["Direct", "Email", "Ad Networks", "Video Ads", "Search Engines"],
  },
  series: [
    {
      name: "Traffic Sources",
      type: "pie",
      radius: "55%",
      center: ["50%", "60%"],
      data: [
        { value: 335, name: "Direct" },
        { value: 310, name: "Email" },
        { value: 234, name: "Ad Networks" },
        { value: 135, name: "Video Ads" },
        { value: 1548, name: "Search Engines" },
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)",
        },
      },
    },
  ],
});

// 在线用户数量组件相关
const { onlineUserCount } = useOnlineCount();

// 记录上一次的用户数量用于计算趋势
const previousCount = ref(0);

// 监听用户数量变化，计算趋势
watch(onlineUserCount, (newCount, oldCount) => {
  if (oldCount > 0) {
    previousCount.value = oldCount;
  }
});

const userStore = useUserStore();

// 当前时间（用于计算问候语）
const currentDate = new Date();

// 问候语：根据当前小时返回不同问候语
const greetings = computed(() => {
  const hours = currentDate.getHours();
  const nickname = userStore.userInfo.nickname;
  if (hours >= 6 && hours < 8) {
    return "晨起披衣出草堂，轩窗已自喜微凉🌅！";
  } else if (hours >= 8 && hours < 12) {
    return `上午好，${nickname}！`;
  } else if (hours >= 12 && hours < 18) {
    return `下午好，${nickname}！`;
  } else if (hours >= 18 && hours < 24) {
    return `晚上好，${nickname}！`;
  } else {
    return "偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！";
  }
});

// 访客统计数据加载状态
const visitStatsLoading = ref(true);
// 访客统计数据
const visitStatsData = ref<VisitStatsVO>({
  todayUvCount: 0,
  uvGrowthRate: 0,
  totalUvCount: 0,
  todayPvCount: 0,
  pvGrowthRate: 0,
  totalPvCount: 0,
});

// 访问趋势日期范围（单位：天）
const visitTrendDateRange = ref(7);
// 访问趋势图表配置
const visitTrendChartOptions = ref();

/**
 * 获取访客统计数据
 */
const fetchVisitStatsData = () => {
  LogAPI.getVisitStats()
    .then((data) => {
      visitStatsData.value = data;
    })
    .finally(() => {
      visitStatsLoading.value = false;
    });
};

/**
 * 获取访问趋势数据，并更新图表配置
 */
const fetchVisitTrendData = () => {
  const startDate = dayjs()
    .subtract(visitTrendDateRange.value - 1, "day")
    .toDate();
  const endDate = new Date();

  LogAPI.getVisitTrend({
    startDate: dayjs(startDate).format("YYYY-MM-DD"),
    endDate: dayjs(endDate).format("YYYY-MM-DD"),
  }).then((data) => {
    updateVisitTrendChartOptions(data);
  });
};

/**
 * 更新访问趋势图表的配置项
 *
 * @param data - 访问趋势数据
 */
const updateVisitTrendChartOptions = (data: VisitTrendVO) => {
  visitTrendChartOptions.value = {
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["浏览量(PV)", "访客数(UV)"],
      bottom: 0,
    },
    grid: {
      left: "1%",
      right: "5%",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: data.dates,
    },
    yAxis: {
      type: "value",
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed",
        },
      },
    },
    series: [
      {
        name: "浏览量(PV)",
        type: "line",
        data: data.pvList,
        areaStyle: {
          color: "rgba(64, 158, 255, 0.1)",
        },
        smooth: true,
        itemStyle: {
          color: "#4080FF",
        },
        lineStyle: {
          color: "#4080FF",
        },
      },
      {
        name: "访客数(UV)",
        type: "line",
        data: data.ipList,
        areaStyle: {
          color: "rgba(103, 194, 58, 0.1)",
        },
        smooth: true,
        itemStyle: {
          color: "#67C23A",
        },
        lineStyle: {
          color: "#67C23A",
        },
      },
    ],
  };
};

// 监听访问趋势日期范围的变化，重新获取趋势数据
watch(
  () => visitTrendDateRange.value,
  () => {
    fetchVisitTrendData();
  },
  { immediate: true }
);

// 组件挂载后加载访客统计数据和通知公告数据
onMounted(() => {
  fetchVisitStatsData();
});
</script>

<style lang="scss" scoped>
.chart {
  height: 400px;
}
.main {
  width: 1920px;
  height: 1080px;
  background: linear-gradient(180deg, #000c1b 0%, #012554 21%, #001125 40%, #000c1b 100%);

  .board-head {
    width: 1920px;
    height: 100px;
    position: relative;

    .head-bg {
      width: 100%;
      height: 114px;
      background-image: url("../../assets/homepage/head.png");
      background-size: 100% 100%;
      position: relative;
      bottom: -14px;
      left: 0;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .yibiao {
      width: 204px;
      margin: 0 84px 34px;
    }
    .logo {
      width: 114px;
      margin-bottom: 34px;
    }
    span {
      width: 114px;
    }
    > img {
      width: 77px;
      height: 39px;
      position: absolute;
      top: 20px;
      left: 40px;
    }
  }

  .board-main {
    width: 1860px;
    height: 926px;
    padding: 0 30px;
    box-sizing: content-box;
    display: flex;
    justify-items: start;
    align-items: flex-start;
    flex-direction: row;

    .main-left,
    .main-right {
      width: 500px;
    }

    .main-right {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: start;
      align-items: center;
    }

    .main-center {
      width: 820px;
      margin: 0 20px;
    }
  }

  .foot-bg {
    width: 1920px;
    height: 54px;
    background-image: url("./imgs/foot.png");
    background-size: 100% 100%;
  }

  .board-main,
  .foot-bg,
  .board-head {
    margin: 0 auto;
  }

  .version-item {
    padding: 16px;
    margin-bottom: 12px;
    background: var(--el-fill-color-lighter);
    border-radius: 8px;
    transition: all 0.2s;

    &.latest-item {
      background: var(--el-color-primary-light-9);
      border: 1px solid var(--el-color-primary-light-5);
    }
    &:hover {
      transform: translateX(5px);
    }
    .version-content {
      margin-bottom: 12px;
      font-size: 13px;
      line-height: 1.5;
      color: var(--el-text-color-secondary);
    }
  }
}
</style>
